<?php

namespace App\Http\Controllers\Asset;

use App\Http\Controllers\Controller;
use App\Http\Resources\AssetResource;
use App\Imports\AssetsImport;
use App\Models\Asset;
use App\Models\AssetStatus;
use Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AssetController extends Controller
{
    use AssetFindOrNewPivotTrait;
    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate(
            [
                'name' => 'required',
                'brand' => 'required',
                'status' => 'required',
                'affiliation' => 'required',
                'keeper' => 'required'
            ],
            [
                'name.required' => '名称字段不能为空',
                'brand.required' => '品牌不能为空',
                'status.required' => '状态不能为空',
                'affiliation.required' => '归属不能为空',
                'keeper.required' => '保管人不能为空'
            ]);
        $assetId = request()->get('id');
        $asset = Asset::findOrNew($assetId);
        $asset->name = request()->get('name');
        $asset->product_model_number = request()->get('product_model_number');
        $asset->category_id = request()->get('category_id');
        $asset->sub_category_id = request()->get('sub_category_id');
        $asset->sn = request()->get('sn');
        $asset->status_id = request()->get('status_id');
        $asset->description = request()->get('description');
        $asset->marking_price = request()->get('marking_price') ?? 0;
        $asset->bid_price = request()->get('bid_price') ?? 0;
        $asset->bid_date = request()->get('bid_date');
        $asset->affiliation_id = $this->getOrNewPivot('affiliation');
        $asset->keeper_id =$this->getOrNewPivot('keeper');
        $asset->brand_id = $this->getOrNewPivot('brand');
        // optional
        $asset->vendor_id = $this->getOrNewPivot('vendor');
        $asset->location_id = $this->getOrNewPivot('location');
        $asset->save();
        // refresh the related pivot tables
        $asset->refresh();
        return response()->json(compact(['asset']));
    }

    public function delete($id)
    {
        $asset = Asset::find($id);
        $result = [
            "success" => false,
            "message" => ""
        ];
        if ($asset->status_id != AssetStatus::LEND) {
            $asset->delete();
            $result['success'] = true;
        } else {
            $result['message'] = "当前状态不可删除";
        }
        return response()->json(compact(['result']));
    }



    public function list(Request $request)
    {
        $result = new AssetResource(collect());
        $itemsPerPage = request()->get('itemsPerPage');
        $page = request()->get('page');
        $sortBy = request()->get('sortBy');
        $query = request()->get('query');

        $AssetQuery = Asset::query();
        if(!empty($query)) {
            $AssetQuery->fuzzyFilter($query);
        }
        if (!empty($sortBy)) {
            $orderByColumn = $sortBy[0];
            $sortDesc = request()->get('sortDesc');
            $sortType = $sortDesc[0] ? 'desc' : 'asc';
            $AssetQuery->orderBy($orderByColumn, $sortType);
        } else {
            $AssetQuery->orderBy('id', 'desc');
        }
        $result = new AssetResource($AssetQuery->paginate($itemsPerPage));
        return $result;
    }

    /**
     * @deprecated
     * @param $orderByColumn
     * @param string $sortType
     * @param $itemsPerPage
     * @return AssetResource
     */
    private function sortByPivotTable($orderByColumn, string $sortType, $itemsPerPage)
    {
        // TODO 还需要研究一下,这个排序会出现错误记录
        $pivotTable = [
            "category_id" => "asset_categories",
            "sub_category_id" => "asset_categories",
            "brand_id" => "asset_brands",
            "status_id" => "asset_statuses",
            "affiliation_id" => "asset_affiliations",
            "keeper_id" => "asset_keepers",
            "vendor_id" => "asset_vendors",
            "location_id" => "asset_locations"
        ];
        $tableName = $pivotTable[$orderByColumn];
        $assets = Asset::join($tableName, "assets.$orderByColumn", '=', "$tableName.id")
            ->orderBy("$tableName.name", $sortType)->paginate($itemsPerPage);
        return new AssetResource($assets);
    }


}
